package com.sure.supermarketserver.stock.purchase.impl;

import com.sure.supermarketserver.common.Utils;
import com.sure.supermarketserver.stock.manage.BranchName;
import com.sure.supermarketserver.stock.purchase.CargoName;
import com.sure.supermarketserver.stock.purchase.PurchaseDto;
import com.sure.supermarketserver.stock.purchase.PurchaseService;
import com.sure.supermarketserver.stock.purchase.SupplierName;
import com.sure.supermarketserver.stock.purchase.dao.PurchaseDao;
import com.sure.supermarketserver.stock.supplier.Supplier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Calendar;
import java.util.List;
import java.util.Map;

//实现类，实现接口
@Service
@Transactional
public class PurchaseServiceImpl implements PurchaseService {

    @Resource
    private PurchaseDao purchaseDao;

    //查询
    @Override
    public Map<String, Object> getPurchaseList(PurchaseDto dto) {

        return Utils.getPage(dto, ()-> purchaseDao.findPurchaseList(dto));

    }


    //增加
    @Override
        public void addPurchase(PurchaseDto dto) {

        try {

            Calendar cal = Calendar.getInstance();
            int year = cal.get(Calendar.YEAR);
            int month = cal.get(Calendar.MONTH) + 1;
            String mom = month < 10 ? ("0" + month) : ("" + month);
            String newNum = purchaseDao.findNewNum(year + mom);
            dto.setIm_id(year + mom + newNum);


            purchaseDao.insertIntoImport(dto);


            List<String> bridlist = purchaseDao.getBranches();
            for (int i = 0; i < bridlist.size(); i++) {
                System.out.println(bridlist.get(i));
                String br_id = bridlist.get(i);
                dto.setBr_id(br_id);
                purchaseDao.insertIntoGoods(dto);
            }
            purchaseDao.updateGoodNum(dto);

//        purchaseDao.insertIntoGoods(dto);
        } catch (Exception e) {
            if (e instanceof RuntimeException) {
                throw e;
            }
            throw new RuntimeException("新增进货订单失败！", e);
        }
    }

    //修改
    @Override
    public void updatePurchase(PurchaseDto dto) {
        purchaseDao.updateImport(dto);
        purchaseDao.updateGoods(dto);
    }

    //删除
    @Override
    public void deletePurchase(Integer id) {

        purchaseDao.deleteGoods(id);
        purchaseDao.deleteImport(id);
    }

    //实现供应商下拉框
    @Override
    public List<SupplierName> findSupplierList() {
        List<SupplierName> supplierList = purchaseDao.findSupplierList();
        return supplierList;
    }

    //实现货物名称下拉框
    @Override
    public List<CargoName> findCargoList() {
        List<CargoName> cargoList = purchaseDao.findCargoList();
        return cargoList;
    }


}
